package com.gengyun.gengyunacquistion.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gengyun.gengyunacquistion.mapper.AcquisitionMapper;
import com.gengyun.gengyunacquistion.pojo.AirConditionHourly;
import com.gengyun.gengyunacquistion.pojo.Indicator;
import com.gengyun.gengyunacquistion.pojo.RecordTime;
import com.gengyun.gengyunacquistion.pojo.SoilConditionHourly;
import com.gengyun.gengyunacquistion.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j

public class AcquisitionServiceImpl implements IAcquisitionService {

    @Autowired
    AcquisitionMapper acqusitionMapper;

    @Autowired
    @Qualifier("airServiceImpl")
    IAirService airService;

    @Autowired
    ISoilService soilService;

    @Autowired
    IIndicatorService indicatorService;

    @Autowired
    IRecordService recordService;

    /**
     * 获取上一次获取数据的时间戳, 用于接着获取数据
     * @return
     */
    public String getLastTimestamp() {
        return acqusitionMapper.selectById(1).getLastTimestamp();
    }



    /**
     * 将json数据保存到txt文档中，
     * @Transactional(rollbackFor = Exception.class)
     * @param content  filePath
     */
    public static boolean createJsonFile(String content, String filePath) {

        // 标记文件生成是否成功
        boolean flag = true;
        // 生成json格式文件
        try {
            // 保证创建一个新文件
            File file = new File(filePath);
            if (!file.getParentFile().exists()) { // 如果父目录不存在，创建父目录
                file.getParentFile().mkdirs();
            }
            if (file.exists()) { // 如果已存在,删除旧文件
                file.delete();
            }
            file.createNewFile();
            // 将格式化后的字符串写入文件
            Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            write.write(content);
            write.flush();
            write.close();
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }




    /**
     * 处理接口获取到的json数据, 这里开启事务管理
     * @Transactional(rollbackFor = Exception.class)
     * @param content
     */
    @Transactional(rollbackFor = Exception.class)
    public void JsonHandler(String content, String endTimestamp) {

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Map<String, String> plotCrop = new HashMap<>();
        plotCrop.put( "16085","雪川哈9-新建1");
        plotCrop.put( "16086","雪川哈9-新建2");
        plotCrop.put( "16080","雪川哈6-新建1");
        plotCrop.put( "16081","雪川哈6-新建2");
        plotCrop.put( "16650","雪川哈6-新建3");
        plotCrop.put( "16651","雪川哈6-新建4");
        plotCrop.put( "16652","雪川哈6-新建5");
        plotCrop.put( "16653","雪川哈6-新建6");
        plotCrop.put( "16654","雪川哈6-新建7");

//        System.out.println(content);

        JSONObject jsonObject = JSON.parseObject(content);
        JSONArray soilConditionHourly = jsonObject.getJSONObject("data").getJSONArray("soilConditionHourly");
        JSONArray airConditionHourly = jsonObject.getJSONObject("data").getJSONArray("airConditionHourly");
        JSONObject indicators = jsonObject.getJSONObject("data").getJSONObject("indicators");

        List<SoilConditionHourly> soilConditionHourlies = handleSoils(soilConditionHourly, plotCrop);
        List<AirConditionHourly> airConditionHourlies = handleAirs(airConditionHourly, plotCrop);
        List<Indicator> indicatorList = handleIndicators(indicators, plotCrop);

        /**
         * 如果不是null, 就插入, 否则会报错, 批处理至少要有一条数据
         * 顺便更新一下数据库 endTimestamp 更新的问题
         */
        List<Long> endTimestampUpdate = new ArrayList<>();

        if (soilConditionHourlies.size() > 0) {
            soilService.saveBatch(soilConditionHourlies, soilConditionHourlies.size());
            Long end = soilConditionHourlies.get(soilConditionHourlies.size()-1).getCreateTimestamp();
            endTimestampUpdate.add(end);
            System.out.println("1:");
            System.out.println(end);
        }
        if (airConditionHourlies.size() > 0) {
            airService.saveBatch(airConditionHourlies, airConditionHourlies.size());
            Long end = airConditionHourlies.get(airConditionHourlies.size()-1).getCreateTimestamp();
            endTimestampUpdate.add(end);
            System.out.println("2:");
            System.out.println(end);
        }
        if (indicatorList.size() > 0) {
            indicatorService.saveBatch(indicatorList, indicatorList.size());
            Long end = indicatorList.get(indicatorList.size()-1).getCollectTimestamp();
            endTimestampUpdate.add(end);
            System.out.println("3:");
            System.out.println(end);
        }
        recordService.updateById(new RecordTime(1, endTimestamp, sf.format(new Date(Long.parseLong(endTimestamp)))));
//        if (endTimestampUpdate.size() > 0) {
//
//            recordService.updateById(new RecordTime(1, endTimestamp, sf.format(Collections.max(endTimestampUpdate))));
//        }

    }


    /**
     * 静态方法用于处理空气json数据
     * @param airConditionHourly
     * @param plotCrop
     * @return
     */
    private static List<AirConditionHourly> handleAirs(JSONArray airConditionHourly, Map<String, String> plotCrop) {

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<AirConditionHourly> airs = new ArrayList<>();

        for (int i = 0; i < airConditionHourly.size(); i++) {
            JSONObject air = (JSONObject) airConditionHourly.get(i);
            Long createTimestamp = Long.parseLong(air.getString("createTimestamp"));
            String cropsRotationPlotId = air.getString("cropsRotationPlotID");
            String plotId = plotCrop.get(cropsRotationPlotId);

    //        System.out.println(cropsRotationPlotId+"   =======>"+plotId);
            String formatTime = sf.format(new Date(createTimestamp));

            Integer humidityFactor = air.getJSONObject("humidity").getInteger("factor");
            Integer humidityUnit = air.getJSONObject("humidity").getInteger("unit");
            Integer humidityValue = air.getJSONObject("humidity").getInteger("value");

            Integer precipitationFactor = air.getJSONObject("precipitation").getInteger("factor");
            Integer precipitationUnit = air.getJSONObject("precipitation").getInteger("unit");
            Integer precipitationValue = air.getJSONObject("precipitation").getInteger("value");

            Integer temperatureFactor = air.getJSONObject("temperature").getInteger("factor");
            Integer temperatureUnit = air.getJSONObject("temperature").getInteger("unit");
            Integer temperatureValue = air.getJSONObject("temperature").getInteger("value");

            AirConditionHourly airCondition = new AirConditionHourly(null,
                    cropsRotationPlotId, createTimestamp, formatTime, plotId,
                    humidityFactor, humidityUnit, humidityValue,
                    precipitationFactor, precipitationUnit, precipitationValue,
                    temperatureFactor, temperatureUnit, temperatureValue
            );

            airs.add(airCondition);
        }
        return airs;
    }

    /**
     * 静态方法, 用于处理土壤的json数据
     * @param soilConditionHourly
     * @param plotCrop
     * @return
     */
    private static List<SoilConditionHourly> handleSoils(JSONArray soilConditionHourly, Map<String, String> plotCrop) {

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<SoilConditionHourly> soils = new ArrayList<>();

        for (int i = 0; i < soilConditionHourly.size(); i++) {
            JSONObject soil = (JSONObject) soilConditionHourly.get(i);
            Long createTimestamp = Long.parseLong(soil.getString("createTimestamp"));
            String deviceBindingSn = soil.getString("deviceBindingSN");
            String cropsRotationPlotId =soil.getString("cropsRotationPlotID");
            String plotId = plotCrop.get(cropsRotationPlotId);
 //           System.out.println(soil);
    //        System.out.println(cropsRotationPlotId+"   =======>"+plotId);
//            String plotId = soil.getString("plotID");
//            String cropRotationPlotId = plotCrop.get(plotId);
            String formatTime = sf.format(new Date(createTimestamp));

            Integer humidityFactor = soil.getJSONObject("humidity").getInteger("factor");
            Integer humidityUnit = soil.getJSONObject("humidity").getInteger("unit");
            Integer humidityValue = soil.getJSONObject("humidity").getInteger("value");

            Integer temperatureFactor = soil.getJSONObject("temperature").getInteger("factor");
            Integer temperatureUnit = soil.getJSONObject("temperature").getInteger("unit");
            Integer temperatureValue = soil.getJSONObject("temperature").getInteger("value");

            SoilConditionHourly soilCondition = new SoilConditionHourly(null,
                    cropsRotationPlotId, createTimestamp, formatTime, deviceBindingSn, plotId,
                    humidityFactor, humidityUnit, humidityValue,
                    temperatureFactor, temperatureUnit, temperatureValue
            );

            soils.add(soilCondition);
        }
        return soils;
    }

    /**
     * 静态方法, 用于处理指标json数据
     * @param indicators
     * @param plotCrop
     * @return
     */
    private static List<Indicator> handleIndicators(JSONObject indicators, Map<String, String> plotCrop) {

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Indicator> indicatorList = new ArrayList<>();
        // 获取所有indicator的key值
        System.out.println(indicators);
        Set<String> keys = indicators.keySet();
        int icount= 0;
        for (String key : keys) {
            JSONArray inds = indicators.getJSONArray(key);
            for (int i = 0; i < inds.size(); i++) {
                icount++;
                JSONObject indicator = (JSONObject) inds.get(i);
                Long collectTimestamp = Long.parseLong(indicator.getString("collectTimestamp"));
                String formatTime = sf.format(new Date(collectTimestamp));
                String cropsRotationPlotId = indicator.getString("cropsRotationPlotID");
                String digitValue = indicator.getString("digitValue");
                String indicatorId = indicator.getString("indicatorID");
                String textValue = indicator.getString("textValue");
                String valueDeterminationType = indicator.getString("valueDeterminationType");

                Indicator indicator1 = new Indicator(
                        null, collectTimestamp, formatTime, cropsRotationPlotId,
                        digitValue, indicatorId, textValue, valueDeterminationType
                );

                indicatorList.add(indicator1);
            }
        }
        System.out.println("总数个数为：=======>" + icount );
        return indicatorList;
    }
}